package ee.ut.cs.mc.madp.p2pdivider.task;

import static ee.ut.cs.mc.madp.p2pdivider.BaseDividerActivity.HANDLER_TOAST;

import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import ee.ut.cs.mc.madp.p2pdivider.BaseDividerActivity;
import ee.ut.cs.mc.madp.p2pdivider.networking.DividerClient;

/**
 * @author Kaarel Jõgeva
 *
 */
public class DividerClientTask extends AsyncTask<InetAddress, Void, Void> {

    public static final String TAG = DividerClientTask.class.getCanonicalName();

    private final Handler handler;
    private final Context context;
    private DividerClient client;

    public DividerClientTask(Handler handler, Context context) {
        this.handler = handler;
        this.context = context;
    }

    @Override
    protected Void doInBackground(InetAddress... params) {
        Log.i(TAG, "Sending greetings...");
        try {
            URI hostUri = new URI("ws://" + params[0].getHostAddress() + ":" + BaseDividerActivity.SERVERPORT);
            client = new DividerClient(handler, context, hostUri);
            client.connect();
            while (!isCancelled()) { // Hold the connection open
                try {
                    Message.obtain(handler, HANDLER_TOAST, "Waiting as client...").sendToTarget();
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }

        } catch (URISyntaxException e) {
            Message.obtain(handler, HANDLER_TOAST, "URI is wrong! " + e.getLocalizedMessage()).sendToTarget();
        } finally {
            if (client != null) {
                client.close();
            }
        }
        return null;
    }
}